import axios from 'axios'
import * as DevUtil from './devEnv'
// create an axios instance
const service = axios.create({
  baseURL: DevUtil.getDevBaseUrl(), // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

// 请求拦截器
service.interceptors.request.use(
  config => {
    config.headers['Content-Type'] = 'application/json'
    return config
  },
  error => {
    return Promise.reject(error)
  }
)

// 响应拦截器
service.interceptors.response.use(
  response => response.data,
  error => {
    let status = 0
    try {
      status = error.response.status
    } catch (e) {
      if (error.toString().indexOf('Error: timeout') !== -1) {
        return Promise.reject(error)
      }
      if (error.toString().indexOf('Error: Network Error') !== -1) {
        return Promise.reject(error)
      }
    }

    // 未登录
    if (status === 401) {
      // 跳转到登陆页面
    }
    return Promise.reject(error.response)
  }
)

export default service
